/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.inventory.actions;

import com.erp.erp.security.logic.SecurityLogic;
import com.erp.erp.security.pojo.Companies;
import com.erp.erp.security.pojo.CompanyRoles;
import com.erp.erp.security.pojo.Stores;
import com.erp.erp.security.pojo.UserCompanies;
import com.erp.erp.security.pojo.UserRoles;
import com.erp.erp.security.pojo.UserStoresPrivileges;
import com.erp.erp.security.pojo.Users;
import com.inventory.helperbeans.CompanyHelperBean;
import com.inventory.helperbeans.UserHelperBean;
import com.inventory.helperbeans.UserRole;
import com.inventory.helperbeans.UserRolesAndStorePriviliges;
import com.inventory.helperbeans.UserStorePrivilegeses;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;

/**
 *
 * @author maha
 */
public class UserAction extends ActionSupport {

    private String userCode;
    private String password;
    private String msg;
    private Vector<UserCompanies> userCompanies = new Vector<UserCompanies>();
    private int companyId;
    private List<Companies> company = new ArrayList<Companies>();
    private Vector<Stores> stores = new Vector<Stores>();
    private Vector<CompanyRoles> companyRoles = new Vector<CompanyRoles>();
    private UserHelperBean user;
    private Vector<Users> users = new Vector<Users>();
    private UserRolesAndStorePriviliges urasp;

    public UserAction() {
    }

    public String login() throws Exception {
        SecurityLogic security = new SecurityLogic();
        Users login = security.login(userCode, password);
        if (login == null) {
            setMsg("Sorry, Seemed to be invalid member or Already Logged In");
        } else {
            Users user = new Users();
            user.setUserSid(login.getUserSid());
            user.setUserName(login.getUserName());
            user.setUserCode(login.getUserCode());
            Map<String, Object> session = ActionContext.getContext().getSession();
            session.put("user", user);
            setMsg("Welcome Back! " + user.getUserName());
            setUserCompanies(security.getUserCompanies(login.getUserSid()));
        }
        return "done";
    }

    public String getUserCompany() {
        SecurityLogic s = new SecurityLogic();
        Companies company = s.getCompany(companyId);
        Map<String, Object> session = ActionContext.getContext().getSession();
        session.put("company", company);
        return "done";
    }

    public String logout() throws Exception {
        SecurityLogic security = new SecurityLogic();
        Map<String, Object> session = ActionContext.getContext().getSession();
        Users get = (Users) session.get("user");
        int logOut = security.logOut(get.getUserSid(), get.getUserCode());
        if (logOut == 1) {
            setMsg("You Logged Out");
            session.remove("user");
            session.remove("company");
        } else {
            setMsg("Can't Logout at a moment");
        }
        return "done";
    }

    //________________________Master Details___________________________
    public String toUser() {
        System.out.println("toUser");
        SecurityLogic security = new SecurityLogic();
        Vector<Companies> companies = security.getCompanies();
        for (Companies companies1 : companies) {
            company.add(companies1);
        }
        setCompany(company);
        return "done";
    }

    public String getUserData() {
        System.out.println("i am about to get user/company data");

        HttpServletResponse response = ServletActionContext.getResponse();
        int register = 0;
        Map<String, Object> session = ActionContext.getContext().getSession();
        Users get = (Users) session.get("user");

        System.out.println(get.getUserSid());

        SecurityLogic security = new SecurityLogic();

        Users newUser = new Users();
        if (getUser().getUserCode() != null) {
            newUser.setActiveFlag(getUser().getActiveFlag());
            newUser.setUserName(getUser().getUserName());
            newUser.setUserCode(getUser().getUserCode());
            newUser.setUserPassword(getUser().getPassword());
            newUser.setUserContactPhone(getUser().getPhone());
            newUser.setUserAddress(getUser().getAddress());
            newUser.setComment(getUser().getComment());
            newUser.setCreationDate(new Date());
            newUser.setEmail(getUser().getEmail());
            Users uzr = new Users();
            uzr.setUserSid(get.getUserSid());
            newUser.setUsersByCreatedBy(uzr);
            register = security.register(newUser);
        }
        if (register == 1) {
            Users insertedUser = security.getUser(getUser().getUserCode());

            //=============== Must insert user and back with id to insert companies===================


            if (user.getCompany() != null) {
                Iterator<CompanyHelperBean> iterator = user.getCompany().iterator();

                while (iterator.hasNext()) {



                    CompanyHelperBean companyHelperBean = iterator.next();
                    System.out.println(companyHelperBean.getId() + "," + get.getUserSid() + "," + companyHelperBean.getCompanyActiveRecord() + "," + insertedUser.getUserSid());

                    UserCompanies companies = new UserCompanies();
                    // companies.setUserCompanySid(companyHelperBean.getId()); The Problem

                    Companies c = new Companies();
                    c.setCompanySid(companyHelperBean.getId());
                    companies.setCompanies(c);

                    companies.setCreationDate(new Date());
                    companies.setUsersByCreatedBy(get);
                    if (companyHelperBean.getCompanyActiveRecord() == null) {
                        companies.setActiveFlag(false);
                    } else {
                        companies.setActiveFlag(companyHelperBean.getCompanyActiveRecord());

                    }
                    companies.setUsersByUserSid(insertedUser);
                    int addUserCompany = security.addUserCompany(companies);
                    System.out.println(addUserCompany + " is it inserted?");

                }
                setMsg("User/User Companies Inserted");
            }
            setMsg("User Inserted");
        } else {
            try {
                response.sendRedirect("error.jsp");
            } catch (IOException ex) {
            }
        }
        return "done";
    }

    public String cuasp() {

        Map<String, Object> session = ActionContext.getContext().getSession();
        Companies comp = (Companies) session.get("company");

        SecurityLogic security = new SecurityLogic();
        users = security.getUsers();
        setUsers(users);

        setCompanyRoles(security.getCompanyRoles(comp.getCompanySid()));
        setStores(security.getCompanyStores(comp.getCompanySid()));
        return "done";
    }

    public String addUserRoleAndStorePriv() {
        SecurityLogic security = new SecurityLogic();
        UserRolesAndStorePriviliges urasp1 = getUrasp();

        //=========== Get createdby and company Id ==================

        Map<String, Object> session = ActionContext.getContext().getSession();
        Users creator = (Users) session.get("user");
        Companies sessionCompany = (Companies) session.get("company");
        //===========================================================
        //=====================get usercmpanysid===================
        int userCompanySID = security.getUserCompanySID(urasp1.getUserId(), sessionCompany.getCompanySid());
        UserCompanies c = new UserCompanies();
        c.setUserCompanySid(userCompanySID);
        //=========================================================
        // System.out.println(urasp1.getActiveRecord() + " " + urasp1.getUserId());
        Iterator<UserRole> iterator = urasp1.getUserRole().iterator();

        while (iterator.hasNext()) {
            UserRole userRole = iterator.next();
            UserRoles roles = new UserRoles();
            roles.setCreationDate(new Date());
            roles.setFromDate(userRole.getFrom());
            roles.setToDate(userRole.getTo());
            roles.setUsersByCreatedBy(creator);
            roles.setUserCompanies(c);
            if (userRole.getActiveFlag() == null) {
                roles.setActiveFlag(false);
            } else {
                roles.setActiveFlag(userRole.getActiveFlag());
            }
            CompanyRoles crole = new CompanyRoles();
            crole.setCompanyRoleSid(userRole.getCompanyRolesSid());
            roles.setCompanyRoles(crole);
            int addUserRoles = security.addUserRoles(roles);
            System.out.println("role addition value=" + addUserRoles);
        }

        Iterator<UserStorePrivilegeses> iterator1 = urasp1.getUserStorePriv().iterator();
        while (iterator1.hasNext()) {
            UserStorePrivilegeses userStorePrivilegeses = iterator1.next();
            UserStoresPrivileges usp = new UserStoresPrivileges();
            usp.setUsersByCreatedBy(creator);
            usp.setCreationDate(new Date());
            usp.setUserCompanies(c);
            usp.setAddPrivilege(userStorePrivilegeses.getAdd());
            usp.setIssuePrivilege(userStorePrivilegeses.getIssue());
            usp.setTransferPrivilege(userStorePrivilegeses.getTransfer());
            usp.setDefaultStore(userStorePrivilegeses.getDefault());
            Stores s = new Stores();
            s.setStoreSid(userStorePrivilegeses.getStoreId());
            usp.setStores(s);
            int addUserStorePriv = security.addUserStorePriv(usp);
            System.out.println("store addition = " + addUserStorePriv);
        }
        return "done";
    }

    //_________________________Accessors(Setters/Getters)______________
    public String getUserCode() {
        return userCode;
    }

    public void setUserCode(String userCode) {
        this.userCode = userCode;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Vector<UserCompanies> getUserCompanies() {
        return userCompanies;
    }

    public void setUserCompanies(Vector<UserCompanies> userCompanies) {
        this.userCompanies = userCompanies;
    }

    public int getCompanyId() {
        return companyId;
    }

    public void setCompanyId(int companyId) {
        this.companyId = companyId;
    }

    public List<Companies> getCompany() {
        return company;
    }

    public void setCompany(List<Companies> company) {
        this.company = company;
    }

    //++++++++++++master detail accessors++++++++++++++
    public UserHelperBean getUser() {
        return user;
    }

    public void setUser(UserHelperBean user) {
        this.user = user;
    }

    public Vector<Users> getUsers() {
        return users;
    }

    public void setUsers(Vector<Users> users) {
        this.users = users;
    }

    public Vector<Stores> getStores() {
        return stores;
    }

    public void setStores(Vector<Stores> stores) {
        this.stores = stores;
    }

    public Vector<CompanyRoles> getCompanyRoles() {
        return companyRoles;
    }

    public void setCompanyRoles(Vector<CompanyRoles> companyRoles) {
        this.companyRoles = companyRoles;
    }

    public UserRolesAndStorePriviliges getUrasp() {
        return urasp;
    }

    public void setUrasp(UserRolesAndStorePriviliges urasp) {
        this.urasp = urasp;
    }
}
